package com.example.forum.controller;

import com.example.forum.entity.Article;
import com.example.forum.entity.Board;
import com.example.forum.entity.User;
import com.example.forum.exception.CustomException;
import com.example.forum.result.Result;
import com.example.forum.services.impl.ArticleServiceImpl;
import com.example.forum.services.impl.BoardServiceImpl;
import com.example.forum.vo.ArticleDetailVO;
import com.example.forum.vo.ArticleVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.example.forum.constant.MessageConstant.*;

@Slf4j
@Tag(name = "文章接口")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;

    @Autowired
    private BoardServiceImpl boardService;

    /**
     * 发布文章
     *
     * @param request
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @PostMapping("/create")
    @Operation(summary = "发布文章")
    public Result create(HttpServletRequest request,
                         @Parameter(description = "板块id") @RequestParam(value = "boardId") @NotNull Long boardId,
                         @Parameter(description = "文章标题") @RequestParam(value = "title") @NotNull String title,
                         @Parameter(description = "文章内容") @RequestParam(value = "content") @NotNull String content) {
        // 判断用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(USER_SESSION);
        if (user.getState() == 1) {
            return Result.error(USER_MUTED);
        }
        // 板块校验
        Board board = boardService.getById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1) {
            return Result.error(ADD_FAILED);
        }
        // 封装文章
        Article article = new Article();
        article.setBoardId(boardId);
        article.setContent(content);
        article.setTitle(title);
        article.setUserId(user.getId());
        // 调用articleService
        try {
            articleService.create(article);
            return Result.success();
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取所有文章
     *
     * @param boardId
     * @return
     */
    @Operation(summary = "获取所有文章")
    @GetMapping("/getAllByBoardId")
    public Result<List<ArticleVO>> getAllByBoardId(@Parameter(description = "板块id") @RequestParam(value = "boardId", required = false) Long boardId) {

        // 判断boardId是否为空
        if (boardId == null) {
            List<ArticleVO> articleVOList = articleService.getAllArticle(null);
            return Result.success(articleVOList);
        }
        return Result.success(articleService.getAllByBoardId(boardId));
    }

    /**
     * 获取文章详情
     *
     * @param articleId
     * @return
     */
    @Operation(summary = "获取文章详情")
    @GetMapping("/details")
    public Result<ArticleDetailVO> details(HttpServletRequest request,
                                           @Parameter(description = "文章id") @RequestParam(value = "id") @NotNull Long articleId) {

        try {
            // 获取用户信息
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(USER_SESSION);
            // 获取文章详情
            ArticleDetailVO articleDetailVO = articleService.getById(articleId);

            // 判断是否为作者
            if (user.getId().equals(articleDetailVO.getUserId())) {
                articleDetailVO.setOwn(true);
            }
            log.info("文章详情: {}", articleDetailVO);
            return Result.success(articleDetailVO);
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改文章
     *
     * @param id
     * @param title
     * @param content
     * @return
     */
    @Operation(summary = "修改文章")
    @PostMapping("/modify")
    public Result modify(HttpServletRequest request,
                         @Parameter(description = "文章id") @RequestParam(value = "id") @NotNull Long id,
                         @Parameter(description = "文章标题") @RequestParam(value = "title") @NotNull String title,
                         @Parameter(description = "文章内容") @RequestParam(value = "content") @NotNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(USER_SESSION);
        try {
            // 获取文章详情
            Article article = articleService.getByIdArticle(id);
            // 判断文章是否存在
            if (article == null) {
                return Result.error(ARTICLE_NOT_EXISTS);
            }
            // 获取登录用户id
            Long userId = article.getUserId();
            // 判断是否为作者
            if (user.getId().equals(userId)) {
                articleService.modify(id, title, content);
                return Result.success();
            } else {
                return Result.error(USER_NOT_PERMISSION);
            }
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新点赞
     *
     * @param id
     * @return
     */
    @Operation(summary = "更新点赞")
    @PostMapping("/thumbsUp")
    public Result thumbsUp(HttpServletRequest request,
                           @Parameter(description = "文章id") @RequestParam(value = "id") @NotNull Long id) {
        // 获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            return Result.error(USER_MUTED);
        }
        try {
            // 更新点赞
            boolean flg = articleService.thumbsUp(id, user);
            return Result.success(flg);
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除文章")
    @PostMapping("/delete")
    public Result delete(HttpServletRequest request,
                         @Parameter(description = "文章id") @RequestParam(value = "id") @NotNull Long id) {
        // 获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(USER_SESSION);
        // 获取文章详情
        Article article = articleService.getByIdArticle(id);
        // 判断文章是否存在
        if (article == null) {
            return Result.error(ARTICLE_NOT_EXISTS);
        }
        // 判断是否为作者
        if (!user.getId().equals(article.getUserId())) {
            return Result.error(USER_NOT_PERMISSION);
        }
        try {
            articleService.delete(id, user.getId(), article.getBoardId());
            return Result.success();
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户所有文章
     *
     * @param userId
     * @return
     */
    @Operation(summary = "获取用户所有文章")
    @GetMapping("/getAllByUserId")
    public Result<List<Article>> getAllByUserId(HttpServletRequest request,
                                                @Parameter(description = "用户id") @RequestParam(value = "userId", required = false) Long userId) {
        // 判断用户id是否为空
        if (userId != null) {
            try {
                return Result.success(articleService.getAllByUserId(userId));
            } catch (CustomException e) {
                log.error(e.getMessage());
                return Result.error(e.getMessage());
            }
        }
        // 获取用户信息
        User user = (User) request.getSession(false).getAttribute(USER_SESSION);

        // 判断用户是否登录
        if (user == null) {
            return Result.error(USER_NOT_LOGIN);
        }

        // 获取用户id, 查寻用户所有文章
        Long id = user.getId();
        try {
            return Result.success(articleService.getAllByUserId(id));
        } catch (CustomException e) {
            log.error(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

}
